package com.yousu.dashijixm.controller;

import com.yousu.dashijixm.pojo.Result;
import com.yousu.dashijixm.pojo.User;
import com.yousu.dashijixm.pojo.UserText;
import com.yousu.dashijixm.service.UserService;
import com.yousu.dashijixm.utils.JwtUtil;
import com.yousu.dashijixm.utils.Md5Util;
import com.yousu.dashijixm.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: YouSu
 * @Version: 1.0
 * @CreateTime: 2023-11-18  12:53
 * 用户管理
 */
//用户管理层

@RestController
@RequestMapping("/user")
@Validated //开启验证
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate; //spring容器没有初始化，所以没有对象

    @PostMapping("/register") //注册
    //用户名和密码要大于4小于16
    //使用了springboot自带的validation使用正则表达式校验用户名和密码
    public Result register(@RequestBody UserText userText
            /*@Pattern(regexp = "^\\S{4,16}$") String username,
                           @Pattern(regexp = "^\\S{5,16}$") String password*/) {
        System.out.println(userText);
        //查询用户
        User u = userService.findByUserName(userText.getUsername());
        if (u == null) {
            //无，注册
            userService.register(userText.getUsername(), userText.getPassword());
            return Result.success();
        } else {
            return Result.error("用户名已使用，请换个名字");
        }
    }

    @PostMapping("/login") //登录
    public Result login(@Pattern(regexp = "^\\S{4,16}$") String username,
                        @Pattern(regexp = "^\\S{5,16}$") String password) {
        User byUserName = userService.findByUserName(username);
        if (byUserName == null) {
            return Result.error("用户不存在,请先注册~");
        }
        if (Md5Util.getMD5String(password).equals(byUserName.getPassword())) {//加密的密码和传过来的密码对应
            //登录成功 返回令牌
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", byUserName.getId());
            claims.put("username", byUserName.getUsername());
            //调用令牌工具类生成令牌
            String token = JwtUtil.genToken(claims);
            //使用redis也可以保存其他信息，为数据库减少负担
            //使用redis缓存令牌，确保修改密码后登录，旧的令牌不能使用
            ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
            //token即作为键又作为值，设置过期时间为1小时
            ops.set(token,token,1, TimeUnit.HOURS);

            //令牌在请求头header中 值为Authorization
            return Result.success(token);
        }
        return Result.error("密码错误~");
    }

    @GetMapping("/userInfo") //获取用户信息
    public Result<User> userInfo(/*@RequestHeader(name = "Authorization") String token*/) {

        //使用ThreadLocal在拦截器保存的令牌获取用户信息,
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        //根据用户名查询用户信息
        User byUserName = userService.findByUserName(username);
        return Result.success(byUserName);
    }

    @PutMapping("/update")//添加用户信息如昵称邮箱等
    public Result update(@RequestBody @Validated User user){
        userService.update(user);
        return Result.success();
    }

    @PatchMapping("/updateAvatar") //更新用户头像
    public Result updateAvatar(@RequestParam @URL String avatarUrl){
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }
    @PatchMapping("/updatePwd")//更新用户密码
    public Result updatePwd(@RequestBody Map<String,String> params,@RequestHeader("Authorization") String token){
        //获取参数
        String old_pwd = params.get("old_pwd");
        String new_pwd = params.get("new_pwd");
        String re_pwd = params.get("re_pwd");
        if (!StringUtils.hasLength(old_pwd) || !StringUtils.hasLength(new_pwd) ||!StringUtils.hasLength(re_pwd) ){
            return Result.error("缺少必要参数");
        }
        //判断旧的密码是否正确
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User byUserName = userService.findByUserName(username);
        if (!byUserName.getPassword().equals(Md5Util.getMD5String(old_pwd))){
            return Result.error("旧密码错误~");
        }
        //检查两次密码是否一样
        if (!new_pwd.equals(re_pwd)){
            return Result.error("两次密码不相同~");
        }
        //更新密码
        userService.updatePwd(new_pwd);
        //更新密码后之前的令牌就不能使用了，在redis中删除旧的令牌
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        System.out.println(token);
        ops.getOperations().delete(token);

        return Result.success();
    }

}
